package middleware

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"go-websocket/internal/dao"
	"go-websocket/internal/model/entity"
	"go-websocket/utility"
)

func VerifyToken(r *ghttp.Request) {

	token := r.Get("_token")

	systemModel := dao.TxzhSystem.Ctx(context.TODO())

	var dbData []*entity.TxzhSystem

	err := systemModel.Where(g.Map{"key": "JWT"}).Scan(&dbData)

	if err != nil {
		r.Response.WriteExit(utility.JsonResult{
			Err: 1,
			Msg: "token校验失败",
		})
	}

	mapValue := dbData[0].Value

	var flag bool
	if keyValue, ok := mapValue["key"].(map[string]interface{});ok {
		if keyStr, ok := keyValue["value"].(string); ok {

			utility.Key = keyStr

			if timeValue, ok := mapValue["time"].(map[string]interface{});ok {
				if timeStrTmp, ok := timeValue["value"].(json.Number); ok {
					var timeStrInt int64
					timeStrInt, err = timeStrTmp.Int64()
					if err != nil {
						r.Response.WriteExit(utility.JsonResult{
							Err: 1,
							Msg: err.Error(),
						})
					}
					utility.TimeNum = int(timeStrInt)
					flag = true
				}
			}

		}
	}

	if flag {
		tokenVal := token.Val()
		verifyToken := utility.VerifyToken(tokenVal.(string))//TODO验证token方法待优化
		if tokenVal == "" || verifyToken == nil {
			r.Response.WriteExit(utility.JsonResult{
				Err: 1,
				Msg: "token无效",
			})
		}

	} else {
		r.Response.WriteExit(utility.JsonResult{
			Err: 1,
			Msg: "token校验失败",
		})
	}

	r.Middleware.Next()
}